const express = require("express");
const router = express.Router();
const sqlClient = require("./config");
const jwt = require("jsonwebtoken");

// 注册业务
router.post("/register", (req, res) => {
  const { acc, pass } = req.body;
  const arr = [acc, pass];
  // 向表中检查用户是否已经存在
  const sqlCheck = "select 1 from user where acc = ? limit 1";
  sqlClient(sqlCheck, arr, (result) => {
    if (result.length == 0) {
      // 该用户不存在表中，则向表中添加数据
      const sql = "insert into user values(null,?,?)";
      sqlClient(sql, arr, (result) => {
        if (result.affectedRows > 0) {
          // 密码加密
          let token = jwt.sign(
            {
              pass,
            },
            "registerkeys"
          );
          res.send({ status: 200, token, acc });
        } else {
          res.send({ status: 401, msg: "注册失败" });
        }
      });
    } else {
      res.send({ status: 401, msg: "用户已经存在" });
    }
  });
});

// 登陆业务
router.post("/login", (req, res) => {
  const { acc, pass } = req.body;
  const sql = "select * from user where acc=? and pass=?";
  const arr = [acc, pass];
  sqlClient(sql, arr, (result) => {
    if (result.length > 0) {
      // 密码加密
      let token = jwt.sign(
        {
          acc,
          id: result[0].id,
        },
        "loginkeys"
      );
      res.send({ status: 200, token, acc });
    } else {
      res.send({ status: 401, msg: "登陆失败" });
    }
  });
});

module.exports = router;
